<!--图片上传组件-->
<template>
  <div class="courseImg">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="percentage"
      :width="178">
    </el-progress>
    <!-- 通过:http-request属性实现自定义上传 -->
    <el-upload
      v-else
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUploading">
      <img v-if="value" :src="value" class="img">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadImg } from '@/services/courses'
export default {
  name: 'courseImg',
  // 在父组件的内部是通过 v-model 绑定的,所以子组件直接通过value接收
  props: {
    value: {
      type: String
    }
  },
  data () {
    return {
      // 是否显示进度条
      isUploading: false,
      // 上传进度百分比
      percentage: 0
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      const isType = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传图片 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isLt2M
    },
    async handleUploading (option) {
      this.isUploading = true
      // 得到被选择的图片信息
      // console.log(option)
      // 创建 FormData 对象保存数据
      const fd = new FormData()
      // 添加数据的键要根据接口文档设置
      fd.append('file', option.file)
      // 发送请求
      const { data } = await uploadImg(fd, (event) => {
        // 设置进度回调,进行百分比计算
        this.percentage = Math.floor(event.loaded / event.total * 100)
      })
      if (data.code === '000000') {
        // 上传成功后,将数据通过自定义事件传递给父组件
        // this.course.courseListImg = data.data.name
        // 通过'input',将数据传给绑定了v-model的父组件
        this.$emit('input', data.data.name)
        this.isUploading = false
        this.percentage = 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .img {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
